package service

import (
	"BiYeProServer/src/model"
	"BiYeProServer/src/model/dao"
	"BiYeProServer/src/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"regexp"
	"strconv"
	"time"
)

func GetQuestions(ctx *gin.Context) {
	var questions []model.Question
	dao.GetDb().Select("id,title,author,author_id,create_time,update_time").
		Find(&questions).
		Limit(10)
	if len(questions) == 0 {
		util.SetResponse(ctx, 5005, false, nil, "获取题目信息失败")
		return
	}
	util.SetResponse(ctx, 200, true, questions, "获取题目信息成功")
}

func SaveQuestion(ctx *gin.Context) {
	var question model.Question
	err := ctx.ShouldBind(&question)
	if err != nil {
		util.SetResponse(ctx, 5006, false, nil, "参数上传错误")
		return
	}
	db := dao.GetDb().Create(&question)
	if db.RowsAffected < 1 {
		util.SetResponse(ctx, 5007, false, nil, "数据库操作错误")
		return
	}
	go func() {
		SaveQuestion2HustOj(&question)
		util.Post(chQuestionStatus, map[string]string{"enable": "启用", "pid[]": fmt.Sprintf("%d", question.Id)})
	}()
	util.SetResponse(ctx, 200, true, question, "保存成功")
}

func ChangeQuestion2Problem(question model.Question) *model.Problem {
	pro := &model.Problem{
		Title:        question.Title,
		Description:  "系统题目",
		SampleInput:  question.SampleInput,
		SampleOutput: question.SampleOutput,
		Spj:          "0",
		Hint:         "没有",
		Source:       "hello",
		InDate:       time.Now(),
		TimeLimit:    1,
		MemoryLimit:  128,
		Defunct:      "N",
		Accepted:     0,
		Solved:       0,
		Submit:       0,
	}
	return pro
}

func SearchQuestionDetail(ctx *gin.Context) {
	idValue := ctx.Query("id")
	id, err := strconv.ParseInt(idValue, 10, 64)
	if err != nil {
		util.SetResponse(ctx, 5009, false, nil, "参数类型错误")
		return
	}
	question := &model.Question{}
	dao.GetDb().Where("id = ?", id).First(&question)
	if question == nil || question.Id < 1 {
		util.SetResponse(ctx, 5010, false, nil, "对应题目不存在")
		return
	}
	SetInputOutputMsg(question)
	util.SetResponse(ctx, 200, true, question, "查询成功")
}

func SetInputOutputMsg(q *model.Question) {
	q.Content += fmt.Sprintf("\n%s\n```\n%s\n```\n\n%s\n```\n%s\n```\n", "## 输入数据", q.SampleInput, "## 输出数据", q.SampleOutput)
}

const saveQuestionUrl = "http://81.70.78.200/admin/problem_add.php"
const chQuestionStatus = "http://81.70.78.200/admin/problem_df_change.php"

func SaveQuestion2HustOj(question *model.Question) string {
	data := map[string]string{
		"problem_id":    fmt.Sprintf("%d", question.Id),
		"title":         question.Title,
		"time_limit":    "1",
		"memory_limit":  "128",
		"description":   question.Content,
		"sample_input":  question.SampleInput,
		"sample_output": question.SampleOutput,
		"input":         question.SampleInput,
		"output":        question.SampleOutput,
		"hint":          "没有",
		"spj":           "0",
		"source":        "hello",
		"postkey":       "1C780FE2F5xx",
		"submit":        "保存",
		"csrf":          "vXN2OQnPfMr83XI4HAjLIN9HgQCyzuqX",
	}
	result := util.Post(saveQuestionUrl, data)
	return result
}

func GetProblemId(result string) string {
	f := regexp.MustCompile(`Problem ID ([\d]{4}) added!`)
	params := f.FindStringSubmatch(result)
	if len(params) < 2 {
		return ""
	}
	return params[1]
}
